<template>

    <!-- 添加或修改对话框 -->
    <el-dialog v-model="open" :title="form.addressId?'修改数据':'新增数据'" width="500px" append-to-body >
        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="收货人姓名" label-width="100" prop="recipientName">
                <el-input v-model="form.recipientName" placeholder="请输入收货人姓名" />
            </el-form-item>

            <el-form-item label="性别" prop="recipientSex">
                 <el-radio-group v-model="form.recipientSex">
                     <template  v-for="item in sys_user_sex" :key="item.value">
                        <el-radio  :label="item.value">{{item.label}}</el-radio>
                     </template>
                </el-radio-group>

            </el-form-item>

             <el-form-item label="收货人电话" label-width="100" prop="phoneNumber">
                <el-input v-model="form.phoneNumber" placeholder="请输入收货人电话" />
            </el-form-item>
<!--            <el-form-item label="省级名称" prop="provinceName">
                <el-input v-model="form.provinceName" placeholder="请输入省级名称" />
            </el-form-item>
            <el-form-item label="市级名称" prop="cityName">
                <el-input v-model="form.cityName" placeholder="请输入市级名称" />
            </el-form-item>
            <el-form-item label="区级名称" prop="districtName">
                <el-input v-model="form.districtName" placeholder="请输入区级名称" />
            </el-form-item> -->

            <el-form-item label="地址" prop="address" size="large">
            <el-cascader
                  size="large"
                  :options="options"
                  v-model="form.address"
                ></el-cascader>
              </el-form-item>

            <el-form-item label="详细地址" prop="detailAddress">
                <el-input v-model="form.detailAddress" placeholder="请输入详细地址" />
            </el-form-item>


<!--            <el-form-item label="岗位顺序" prop="postSort">
                <el-input-number v-model.number="form.postSort" controls-position="right" :min="0" />
            </el-form-item> -->

           <el-form-item label="默认" prop="isDefault">
                 <el-radio-group v-model="form.isDefault">
                     <template  v-for="item in sys_yes_no" :key="item.value">
                        <el-radio  :label="item.value">{{item.label}}</el-radio>
                     </template>
                </el-radio-group>

            </el-form-item>

            <el-form-item label="标签" prop="label">
                <el-input v-model="form.label" placeholder="请输入标签"  :rows="2" type="textarea" />
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>

</template>

<script lang="ts" setup>
    import { reactive, ref,getCurrentInstance, ComponentInternalInstance  } from 'vue'
    import { type FormRules, type FormInstance, ElMessage } from 'element-plus';

    // 引用后台的api
    import { getAddresses,addAddresses,updateAddresses } from '@/api/app/store/addresses';
    import { FormReq } from '@/types/store/storeAddresses';
    import {
        regionData, // 省市区三级联动数据
        codeToText, // 是个大对象，属性是区域码，属性值是汉字 用法例如：codeToText['110000']输出北京市
      } from "element-china-area-data";
      // 定义响应式数据
      const options = ref(regionData);

    // 获取当前vue3的页面this对象转换为proxy代理，查询 sys_dict_data表中的值
    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    const { sys_user_sex } = proxy!.useDict('sys_user_sex');
    const { sys_yes_no } = proxy!.useDict('sys_yes_no');

    const open = ref(false);
    //得到数据表单form样式对象
    const formRef = ref<FormInstance>();

    //声明子组件的自定义事件 https://cn.vuejs.org/api/sfc-script-setup.html#defineprops-defineemits
    const emit = defineEmits(['refreshDataList'])

   // 定义表单对象
   const form = ref<FormReq>({
       addressId: undefined,
       recipientName: '',
       phoneNumber: '',
       provinceName: '',
       cityName: '',
       districtName: '',
       provinceCode : '',
       cityCode:'',
       districtCode : '' ,
      address:[],
       recipientSex:'0',
       detailAddress: '',
       label : '',
       isDefault : '0',
   });


   // 表单验证
   const rules = reactive<FormRules>({
       recipientName: [
           { required: true, message: '该值不能为空', trigger: 'blur' }
       ],
       phoneNumber: [
           { required: true, message: '该值不能为空', trigger: 'blur' }
       ],
       detailAddress: [
           { required: true, message: '该值不能为空', trigger: 'blur' }
       ],
       recipientSex: [
           { required: true, message: '该值不能为空', trigger: 'blur' }
       ],
   });

   //对话框保存按钮
   const submitForm = () => {
     formRef.value.validate((valid: boolean) => {
           //验证不成功
       	if (!valid) {
       		return false
       	}

// 从 address 数组中提取省市区名称
  let provinceName = '';
  let cityName = '';
  let districtName = '';
  let provinceCode = '';
  let cityCode='';
  let districtCode = '' ;

    const addressDetail = form.value.address;

    provinceCode = addressDetail[0] || '';
    cityCode=addressDetail[1] || '';
    districtCode=addressDetail[2] || '';
    provinceName = codeToText[addressDetail[0]] || '';
    cityName = codeToText[addressDetail[1]] || '';
    districtName = codeToText[addressDetail[2]] || '';


  // 将提取的值赋给对应的字段
  form.value.provinceName = provinceName;
  form.value.cityName = cityName;
  form.value.districtName = districtName;
  form.value.provinceCode = provinceCode;
  form.value.cityCode = cityCode;
  form.value.districtCode = districtCode;

        //修改
        if(form.value.addressId){
             updateAddresses(form.value).then(resp=>{
                 ElMessage.success({
                        message: '修改成功',
                        duration: 500,
                        onClose: () => {
                            //关闭弹窗
                            open.value = false
                          //调用重新查询数据操作
                            emit('refreshDataList')
                        }
                    });

             })
        }else{
            //新增
            addAddresses(form.value).then(resp=>{
                ElMessage.success({
                       message: '新增成功',
                       duration: 500,
                       onClose: () => {
                           //关闭弹窗
                           open.value = false
                         //调用重新查询数据操作
                           emit('refreshDataList')
                       }
                   });

             })
        }

      })

   };

   //对话框取消按钮
   const cancel = () => {
       open.value = false;
       resetForm();

   };


   // 重置表单
   const resetForm = () => {
       // 清空表单样式
       if (formRef.value){
           formRef.value.resetFields();
       }
       // 重置值
       form.value = {
       recipientName: '',
       phoneNumber: '',
       provinceName: '',
       cityName: '',
       districtName: '',
       provinceCode : '',
       cityCode:'',
       districtCode : '' ,
       address:[

    ],
       recipientSex:'0',
       detailAddress: '',
       label : '',
       isDefault : '0'
       };
   };

   //判断如果是修改操作，就要查询数据库，还原数据,要暴露出去
   const init = (addressId?: number) => {
       open.value = true
       // 重置表单数据
       resetForm();
       // addressId 存在则为修改
       if (addressId) {
           getAddresses(addressId).then(resp => {
               // 假设 resp.data 是一个对象
                           const formData = resp.data || {}; // 确保 formData 是一个对象，以防 resp.data 是 undefined

                           // 检查 address 属性是否存在且为数组
                           if (!Array.isArray(formData.address)) {
                               // 如果不存在或不是数组，则创建一个新的数组
                               formData.address = [];
                           }

                           // 将 provinceCode, cityCode, districtCode 推入 address 数组
                           formData.address.push(formData.provinceCode, formData.cityCode, formData.districtCode);
                           // 更新表单数据
                           form.value = formData;


           })
       }
  }

       //https://cn.vuejs.org/api/sfc-script-setup.html#defineexpose
       defineExpose({
           init
       })









</script>

<style>
</style>
